<!-- components/lrc-component.vue -->
<script setup  lang="uts">
import { ref, watch, onMounted } from 'vue'
import { getLyricAPI } from '@/apis/music.uts'

const props = defineProps({
  songId: {
    type: [Number, String],
    required: true
  },
  currentTime: {
    type: Number,
    default: 0
  },
  activeColor: {
    type: String,
    default: '#fff'
  },
  inactiveColor: {
    type: String,
    default: 'rgba(255,255,255,0.6)'
  }
})

interface LrcItem {
  time: number
  text: string
}

const lrcList = ref<LrcItem[]>([]) as any
const currentIndex = ref(0)
const scrollTop = ref(0)
const lineHeight = 50

// 使用闭包实现持久化缓存
const lyricCache = (() => {
  const cache = new Map<string | number, LrcItem[]>()
  return {
    get: (id: string | number) => cache.get(id),
    set: (id: string | number, value: LrcItem[]) => cache.set(id, value),
    has: (id: string | number) => cache.has(id)
  }
})()

// 解析歌词
const parseLrc = (lrc: string) => {
  const lines = lrc.split('\n')
  const result: LrcItem[] = []
  const timeReg = /\[(\d{2}):(\d{2}\.\d{2,3})\]/
  
  lines.forEach(line => {
    const matches = timeReg.exec(line)
    if (matches) {
      const text = line.replace(timeReg, '').trim()
      const minutes = parseFloat(matches[1])
      const seconds = parseFloat(matches[2])
      const time = minutes * 60 + seconds
      result.push({ time, text })
    }
  })
  
  return result.sort((a, b) => a.time - b.time)
}

// 增强版获取歌词
const getLyric = async (id: any) => {
  if (!id) {
    console.error('无效的歌曲ID')
    return
  }

  // 优先从缓存读取
  if (lyricCache.has(id)) {
    lrcList.value = lyricCache.get(id)!
    return
  }

  try {
    const res = await getLyricAPI(id)
    const lrc = res.lrc?.lyric || ''
    const parsed = parseLrc(lrc)
    // 写入缓存并立即更新
    lyricCache.set(id, parsed)
    lrcList.value = parsed
  } catch (error) {
    console.error('获取歌词失败:', error)
    lrcList.value = []
  }
}

// 更新当前歌词
const updateCurrentLine = (time: number) => {
  if (!lrcList.value.length) return
  
  // 找到最后一个小于等于当前时间的歌词索引
  let index = lrcList.value.length - 1
  while (index >= 0 && lrcList.value[index].time > time) {
    index--
  }
  currentIndex.value = Math.max(0, index)
  
  // 计算滚动位置
  const maxScroll = (lrcList.value.length - 1) * lineHeight
  scrollTop.value = Math.min(currentIndex.value * lineHeight, maxScroll)
}

// 双重保险监听
watch(() => props.songId, (newVal) => {
  if (newVal) {
    // 强制重置滚动位置
    currentIndex.value = 0
    scrollTop.value = 0
    // 立即同步设置缓存内容
    if (lyricCache.has(newVal)) {
      lrcList.value = lyricCache.get(newVal)!
    }
    // 异步获取最新歌词
    getLyric(newVal)
  }
}, { immediate: true, flush: 'post' })

// 增强时间监听
watch(() => props.currentTime, (newVal) => {
  if (!lrcList.value.length) return

  const lastLineTime = lrcList.value[lrcList.value.length - 1]?.time || 0
  
  // 处理播放完成情况
  if (newVal > lastLineTime || newVal === 0) {
    currentIndex.value = 0
    scrollTop.value = 0
  } else {
    updateCurrentLine(newVal)
  }
})

// 挂载时强制同步缓存
onMounted(() => {
	const id:any =props.songId
  if (id && lyricCache.has(id)) {
    lrcList.value = lyricCache.get(id)
  }
})

// 组件卸载时保持缓存
</script>
<template>
  <view class="lrc-container">
    <scroll-view 
      :scroll-top="scrollTop" 
      scroll-y 
      class="scroll-view" 
      :scroll-with-animation="true"
    >
      <view 
        v-for="(item, index) in lrcList" 
        :key="index" 
        class="lrc-line"
        :class="{ active: currentIndex === index }"
        :style="{ 
          color: currentIndex === index ? props.activeColor : props.inactiveColor,
          height: `${lineHeight}px`
        }"
      >
        {{ item.text || '' }}
      </view>
    </scroll-view>
  </view>
</template>


<style scoped>
.lrc-container {
  height: 300rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.scroll-view {
  height: 100%;
  text-align: center;
}

.lrc-line {
	text-align: center;
  font-size: 20rpx;
  font-weight: 700;
  line-height: 50rpx;
  transition: all 0.3s;
  white-space: nowrap;
}

.lrc-line.active {
  font-size: 35rpx;
  font-weight: bold;
}

/* 微信小程序样式适配 */
@media mp-weixin {
  .scroll-view {
    width: 100%;
  }
  
  .lrc-line {
    transform: translateZ(0); /* 解决微信滚动性能问题 */
  }
}
</style>